package com.example.myapplication.util

import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.ContextCompat
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream

object ImageSaveUtil {
    private val client = OkHttpClient()

    // 下载图片字节（suspend，可在 IO dispatcher 中调用）
    suspend fun downloadImageBytes(url: String): ByteArray? {
        return try {
            val request = Request.Builder().url(url).build()
            val response = client.newCall(request).execute()
            response.use {
                if (!it.isSuccessful) return null
                it.body?.bytes()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 保存图片到相册，兼容 Android Q+ (MediaStore) 与低版本（外部存储）
    // 返回是否成功
    fun saveImageToGallery(context: Context, imageBytes: ByteArray, fileName: String): Boolean {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10 及以上，通过 MediaStore 写入公共图片集合
                val resolver = context.contentResolver
                val contentValues = ContentValues().apply {
                    put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                    put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
                    put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
                    put(MediaStore.Images.Media.IS_PENDING, 1)
                }
                val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
                    ?: return false
                resolver.openOutputStream(uri).use { out ->
                    out ?: return false
                    out.write(imageBytes)
                }
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                resolver.update(uri, contentValues, null, null)
                true
            } else {
                // Android 9 及以下：写到外部存储目录，需 WRITE_EXTERNAL_STORAGE 权限
                val picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                if (!picturesDir.exists()) picturesDir.mkdirs()
                val file = File(picturesDir, fileName)
                FileOutputStream(file).use { fos ->
                    fos.write(imageBytes)
                }
                // 通知媒体库刷新（有些设备需要）
                try {
                    val uri = android.net.Uri.fromFile(file)
                    val intent = android.content.Intent(android.content.Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                    intent.data = uri
                    context.sendBroadcast(intent)
                } catch (ignored: Exception) {
                }
                true
            }
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
}

object PermissionUtils {
    fun hasPermission(context: Context, permission: String): Boolean {
        val granted = ContextCompat.checkSelfPermission(context, permission)
        return granted == android.content.pm.PackageManager.PERMISSION_GRANTED
    }
}